import React from 'react'
import { Table, Popconfirm, Input, InputNumber, Form, Space, message } from 'antd';
import { useEffect, useState } from 'react';

import { useGetpublicpropsQuery,usePuteditpublicpropsMutation } from '../../store/request/datamonitorrequests/publicpropsrequest';

const PublicProps = () => {
  
  const [messageApi, contextHolder] = message.useMessage();
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  const getRandomuserParams = (params) => ({
    pagesize: params.pagination?.pageSize,
    page: params.pagination?.current,
    
    //...params,
  });
  const [editingKey, setEditingKey] = useState(''); // 初始化正在编辑的 key 的 state
  
  //tableParams发生变化就会执行发送请求和参数
  const result = useGetpublicpropsQuery(getRandomuserParams(tableParams));
  
  const [edittrigger] = usePuteditpublicpropsMutation();
  
  const [form] = Form.useForm(); // 从 Form.useForm() 中解构 form
  const isEditing = (record) => record.key === editingKey; // 定义 isEditing 函数以检查记录是否正在被编辑

  

  // 定义 edit 函数以将 editingKey state 设置为记录的 key
  //表单更新数据只能用setFieldsValue方法，不能用setstate方法，这样就能获取原始值
  const edit = (record) => {

    form.setFieldsValue({

      sample: record.sample,
      points: record.points,
      reducetimes: record.reducetimes,
      accerrorvalue: record.accerrorvalue,
      autorizedkey: record.autorizedkey,
      intervaltime:record.intervaltime,
      fromemail: record.fromemail,
      modeltext:record.modeltext,
      diserrorvalue: record.diserrorvalue,
    
      smtaddress:record.smtaddress,
      smtpport: record.smtpport,
      subject: record.subject,
      timespan:record.timespan,
      logkeywords:record.logkeywords



      //...record,  //一展开record，就会报错date.locale is not a function，但是之前arriveddate已经赋值为空字符串，所以除了arriveddate为空外，其余属性按照record展开
    });

    setEditingKey(record.key);
  };

  const messageerror = (editordel) => {
    //message.success('This is a success message');
    if (editordel === 0) {
      messageApi.open({
        type: 'error',
        content: '编辑失败',
      });
    }
    else if (editordel === 1) {
      messageApi.open({
        type: 'error',
        content: '删除失败',
      });
    }
    else if (editordel === 2){
      messageApi.open({
        type: 'error',
        content: '添加失败',
      });
    }
    
    //console.log("消息框");
  };
  const messagesucess = (editordel) => {
    if (editordel === 0) {
      messageApi.open({
        type: 'success',
        content: '编辑成功',
      });
    }
    else if (editordel === 1) {
      messageApi.open({
        type: 'success',
        content: '删除成功',
      });
    }
    else if (editordel === 2){
      messageApi.open({
        type: 'success',
        content: '添加成功',
      });
    }
    
  };


  //这个方法页面加载时就会不停的执行
  const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => { // 定义 EditableCell 组件并传入 props

    return (
      <td {...restProps}>
        {editing ? ( // 如果正在编辑，渲染带有相应 props 的 inputNode
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required:  true,
                message: `请输入${title}!`,
              },
            ]}
          >
            {dataIndex === "autorizedkey"||dataIndex === "fromemail"||dataIndex === "smtaddress"||dataIndex === "subject"||dataIndex === "logkeywords" ? <Input /> : <InputNumber min={0} />}
          </Form.Item>
        ) : (
          children // 否则渲染 children（文本）
        )}
      </td>
    );
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      editable: false,
    
      //render: (name) => `${name.first} ${name.last}`,

    },
    {
      title: '采样频率',
      dataIndex: 'sample',
      editable: true,

      // width: '8%',
    },
    {
      title: '点数',
      dataIndex: 'points',
      editable: true,

    },
    {
      title: '定时间隔',
      dataIndex: 'intervaltime',
      editable: true,

    },
    {
      title: '降采样倍数',
      dataIndex: 'reducetimes',
      editable: true,

      // width: '10%',
    },
    {
      title: '发送方',
      dataIndex: 'fromemail',
      editable: true,

    },
    {
      title: '服务器地址',
      dataIndex: 'smtaddress',
      editable: true,

    },
    {
      title: '端口',
      dataIndex: 'smtpport',
      editable: true,

    },
    {
      title: '主题',
      dataIndex: 'subject',
      editable: true,

    },
    {
      title: '模板信息',
      dataIndex: 'modeltext',
      editable: true,

    },
    {
      title: '异常发送间隔',
      dataIndex: 'timespan',
      editable: true,

    },
    {
      title: '密码',
      dataIndex: 'autorizedkey',
      editable: true,

    },
    {
      title: '加速度极限值',
      dataIndex: 'accerrorvalue',
      editable: true,

    },
    {
      title: '位移极限值',
      dataIndex: 'diserrorvalue',
      editable: true,

    },
    {
      title: '日志关键词',
      dataIndex: 'logkeywords',
      editable: true,

    },
    {
      //表格最后的操作按钮
      title: '操作',
      dataIndex: 'action',
      width: '15%',
      render: (_, record) => { // 使用 Popconfirm 组件渲染操作列
        const editable = isEditing(record);//判断这一行的key是否为editingKey，如果是则说明点击了edit，如果不是则说明没有点击

        return editable ? (

          <span>
            <a onClick={() => save(record.key)} style={{ marginRight: 8 }}>
              保存
            </a>
            <Popconfirm title="确定取消吗?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>

        ) : (
          //点击了edit就把这一行的key设为editingKey，重新渲染，然后editable变为true，显示保存和取消a标签，editingKey不等于空说明有行点了edit，则其他行都是disabled
          <Space size="middle">
            <a disabled={editingKey !== ''} onClick={() => edit(record)}>
              编辑
            </a>

          </Space>
        );

      },
    },
  ];

  const save = async (key) => {
    //这里的row就是表单的所有项的值作为一个row对象存储
    //这里会异步
    const row = await form.validateFields();

    row.key = key;
    //发送put请求到服务器
    const r = await edittrigger(row).unwrap();
    //console.log(r);
    if (r.code === 200) {
      //console.log("成功")
      messagesucess(0);

    } else {
      messageerror(0);
    }
    setEditingKey('');//取消编辑的选项

  };

  const cancel = () => { // 定义 cancel 函数以重置 editingKey state
    setEditingKey('');//取消编辑的选项

  };
  
  const handleTableChange = (pagination, filters, sorter) => {

    setTableParams({
      pagination,
      //filters,
      // ...sorter,
    });

    // pagination分页数据如果和tableParams里的分页数据不一样，就把数据清零，重新发送请求
    // if (pagination.pageSize !== tableParams.pagination?.pageSize) {
    //   setData([]);
    // }
  };
  //这个比EditableCell先执行，这个是点了edit后展示的form表单的设置
  const mergedColumns = columns.map((col) => { // 通过映射 columns 数组定义 mergedColumns 数组
    if (!col.editable) { // 如果列不可编辑，返回列
      return col;
    }

    return {
      ...col, // 否则返回编辑行新对象，其 render 函数为 EditableCell 组件
      onCell: (record) => (

        {

          record,
          //inputType: col.dataIndex === 'category' ? 'radio' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(record),//判断这一行的key是否为editingKey，为true说明这一行点击了edit
          // 将单元格的原始值传递给 EditableCell 组件

        }),
    };
  });

  //一旦tableParams发生改变，就调用此方法，当然第一次加载页面的时候也会调用此方法，所以第一次总是会去发送请求
  //useEffect 钩子函数将在组件渲染后执行 
  useEffect(() => {
    //如果请求成功则调用setTableParams方法

    if (result.isSuccess) {
      //console.log(result.data.pagedata);
      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: result.data.data.total,

        },
      });
    }

  }, [JSON.stringify(tableParams)]);




  return (
    <>
      {/* 必须把contextHolder包裹整个组件才能显示message消息框 */}
      {contextHolder}
   
      <Form form={form} component={false}>

        <Table
          components={{
            body: {
              cell: EditableCell, // 使用 EditableCell 组件作为表格单元格
            },
          }}
          bordered
          
          dataSource={result.isSuccess ? result.data.data.pagedata : []} // 将 dataSource prop 设置为数据 state
          columns={mergedColumns} // 将 columns prop 设置为 mergedColumns 数组
          rowClassName="editable-row"
          pagination={tableParams.pagination}
          loading={result.isLoading}
          onChange={handleTableChange}

        />
     

      </Form>


    </>
  )
}

export default PublicProps